package me.chenjp.tracker.core.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author: Chenjp
 * @description: 这个人很懒, 没有留下任何注释
 * @create: 2019-05-03 13:07
 */
@Slf4j
@Component
public class JwtCache<K, V> {
    private final Lock lock = new ReentrantLock();
    private final int maxCapacity = 10000;
    private final Map<K, V> eden;
    private final Map<K, V> perm;

    public JwtCache() {
        this.eden = new ConcurrentHashMap<>(this.maxCapacity);
        this.perm = new WeakHashMap<>(this.maxCapacity);
    }

    public V get(K k) {
        V v = this.eden.get(k);
        if (v == null) {
            lock.lock();
            try {
                v = this.perm.get(k);
            } finally {
                lock.unlock();
            }
            if (v != null) {
                this.eden.put(k, v);
            }
        }
        return v;
    }

    public void put(K k, V v) {
        if (this.eden.size() >= maxCapacity) {
            lock.lock();
            try {
                this.perm.putAll(this.eden);
            } finally {
                lock.unlock();
            }
            this.eden.clear();
        }
        this.eden.put(k, v);
    }

    public void remove(K k) {
        // V vExist = this.eden.getFile(k);
        // if (v != null) {
        lock.lock();
        try {
            log.info("删除缓存: {}", k);
            this.perm.remove(k);
            this.eden.remove(k);
            log.info("成功删除缓存: {}", k);
        } finally {
            lock.unlock();
        }
    }
}